package com.ITXu.reggie.service.serviceImpl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ITXu.reggie.DTO.DishDto;
import com.ITXu.reggie.entity.Category;
import com.ITXu.reggie.entity.Dish;
import com.ITXu.reggie.entity.DishFlavor;
import com.ITXu.reggie.mapper.DishMapper;
import com.ITXu.reggie.service.CategoryService;
import com.ITXu.reggie.service.DishFlavorService;
import com.ITXu.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService{
	
	@Autowired
	public DishFlavorService dishFlavorService;
	
	@Autowired
	public DishService dishService;
	

	@Override
	public void saveWithDishFlavor(DishDto dto) {
		//先调用dishservice的save方法，用dto存入新dish对象的数据
		this.save(dto);
		//从dto取得dishId
		Long dishId = dto.getId();
		//取得dto中的flavors集合，遍历该集合，对每个单体增加一条属性dishId
		List<DishFlavor> flavors = dto.getFlavors();
		for (DishFlavor dishFlavor : flavors) {
			dishFlavor.setDishId(dishId);
		}
		//打印新的flavors
		log.info(flavors.toString());
		//调用dishFlavorService的saveBatch方法，将flavors数组存入
		dishFlavorService.saveBatch(flavors);
	}

	@Override
	public DishDto getFlavorsAndDishById(Long id) {
		//从dish表查信息获得dish对象
		Dish dish = dishService.getById(id);
		//从dish_flavor表查信息获得flavors
		LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(DishFlavor::getDishId, id);
		List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
		//给dishdto赋值dish
		DishDto dishDto = new DishDto();
		BeanUtils.copyProperties(dish, dishDto);
		//给dishdto赋值flavors
		dishDto.setFlavors(flavors);
		return dishDto;
	}

	@Override
	public void upateWithFlavor(DishDto dto) {
		//更新dish对象(dto对象是dish的子类，可以直接传参到updatebyid方法中)
		this.updateById(dto);
		//在dishflavor表中删除dishdto原先的flavors
		Long dishId = dto.getId();
		LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
		//删除条件，根据当前id删除dishflavor表中对应id的对象
		queryWrapper.eq(DishFlavor::getDishId, dishId);
		dishFlavorService.remove(queryWrapper);
		//在dishflavor中插入新的对象（调用saveBatch方法直接传入dto中的flavors数组）
		List<DishFlavor> updatedFlavors = dto.getFlavors();
		for (DishFlavor dishFlavor : updatedFlavors) {
			dishFlavor.setDishId(dishId);
		}
		dishFlavorService.saveBatch(updatedFlavors);
	}
	
}
